package cn.kgc.ssmmodulardemo.controller;

import cn.kgc.ssmmodulardemo.entity.User;
import cn.kgc.ssmmodulardemo.entity.vo.AddUserVO;
import cn.kgc.ssmmodulardemo.service.UserService;
import com.alibaba.fastjson.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public  Object userLogin(@RequestParam("userCode")String userCode,
                             @RequestParam("userPassword")String userPassword,
                             HttpSession httpSession){
        JSONObject jsonObject=new JSONObject();
        //要传输的数据
        String data="";
        //要传输的信息
        String massage="";
        //状态码！ 自定义
        String statCode="";
        User user=new User();
        user.setUserCode(userCode);
        user.setUserPassword(userPassword);
        User result=userService.userLogin(user);
        if (result!=null){
            data=result.toString();
            massage="登陆成功";
            statCode="10000";
        }else {
            data="";
            massage="用户名或 密码错误";
            statCode="10001";
        }
        jsonObject.put("data",data);
        jsonObject.put("massage",massage);
        jsonObject.put("statCode",statCode);
        return jsonObject.toJSONString();
    }

    /**
     * valid 用来帮我们校验数据的合法性
     * @param addUserVO 视图对象， 要求该对象的属性内容必须要和前段传过来的值一样
     * @param result 用来 返回对象是否合法
     * @return 返回视图模型 如果返回到success 页面 否则跳到error页面
     */
    @RequestMapping("/add")
    public ModelAndView testAdd(@Valid AddUserVO addUserVO, BindingResult result){
ModelAndView modelAndView=new ModelAndView();
        if (result.hasErrors()){
            System.out.println("检测到数据的不合法性。。。错误信息如下");
            System.out.println(result.getFieldError().toString());
            modelAndView.setViewName("error");
        }else {
            modelAndView.setViewName("success");
        }
        return  modelAndView;

    }
}
